package command.client;

import client.ClientSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.MessageCommunication;
import model.User;

public class DisconnectConversationClient implements CommandClient {

    private String conversationID;

    public DisconnectConversationClient() {
    }

    public void setConversationID(String idOfTheConversation) {
        conversationID = idOfTheConversation;
    }

    @Override
    public void execute(ClientSession clientSession, boolean isInvokedByTheServer) {
        try {
            if (isInvokedByTheServer) {
                MessageCommunication message = (MessageCommunication) clientSession.getObjectInputStream().
                        readObject();
                Object o = clientSession.getObjectInputStream().readObject();
                ArrayList<User> usersList = (ArrayList<User>) o;
                clientSession.getGUIChatPrincipal().getConversations().get(message.getMessage()).
                        updateUserChatList(usersList);
            } else {
                clientSession.getObjectOutputStream().writeObject(
                        new MessageCommunication(true, "disconnectconversationserver"));
                clientSession.getObjectOutputStream().flush();
                clientSession.getObjectOutputStream().writeObject(new MessageCommunication(true, conversationID));
                clientSession.getObjectOutputStream().flush();
                clientSession.getObjectOutputStream().writeObject(clientSession.getUserSession());
                clientSession.getObjectOutputStream().flush();
            }
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(DisconnectConversationClient.class.getName()).log(Level.SEVERE,
                    "Fallo al realizar el abandono de una conversacion en el cliente", ex);
        }
    }
}
